<?php
/**
 * Svick a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://svick.tomener.com/
 * Since: 2022
 */

namespace lib\wechat;

use Exception;
use Svick\Core\App;
use Svick\Helper\Helper;
use Svick\Http\Client\Http;
use Svick\Log\Log;

class QrcodeLib
{
    /**
     * 获取字符串临时二维码
     *
     * @param $scene string 场景值，最长64位
     * @param $expire
     * @return string
     * @throws Exception
     */
    public static function genTemporaryQrcodeString(string $scene, $expire): string
    {
        if (App::$env == 'dev') {
            return 'https://weixin.svick.com/q/' . Helper::random(20);
        }

        $api_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . AccessToken::mp();
        $res = Http::asJson()->post($api_url, [
            'expire_seconds' => $expire,
            'action_name' => 'QR_STR_SCENE',
            'action_info' => ['scene' => ['scene_str' => $scene]]
        ]);
        if ($res->status() != 200) {
            throw new Exception('get access token error');
        }
        $ret = $res->array();
        if (isset($ret['errcode']) || !isset($ret['url'])) {
            Log::single(['errcode' => $ret['errcode'], 'errmsg' => $ret['errmsg']], 'gen_temporary_qrcode.err');
            throw new Exception('gen temporary qrcode error');
        }
        //{"ticket":"xxx==","expire_seconds":60,"url":"http://weixin.qq.com/q/kZgfwMTm72WWPkovabbI"}

        return $ret['url'];
    }
}
